<template>
  <div class="margin-container-list">
    <!-- 操作区域 -->
    <div class="pad-t-20 pad-b-20">
      <el-input @keyup.enter.native="handleSearch" v-model="keyword" placeholder="请输入任务名称"
                style="width: 300px"></el-input>
      <el-select v-model="taskAmountType" placeholder="请选择" @change="changeType">
        <el-option
          v-for="item in payStatus"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-select v-model="activeName" placeholder="请选择" @change="changeType">
        <el-option
          v-for="item in payTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker
        v-model="starEndTime"
        type="daterange"
        unlink-panels
        range-separator="至"
        value-format="yyyy-MM-dd HH:mm:ss"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-button type="primary" @click="handleSearch">查询</el-button>
    </div>
    <div class="table-container">
      <el-table :data="taskInfoList" @sort-change="sortChange" @selection-change="handleSelectionChange"
                v-loading="listLoading" element-loading-text="加载中"
                style="width: 300%">
        <el-table-column min-width="240px" label="任务名称" prop="taskName">
        </el-table-column>
        <template v-if="taskAmountType == '2'">
          <el-table-column width="240px" label="追加酬金" prop="amount">
            <template slot-scope="scope">
              <div>¥{{ scope.row.amount }}</div>
            </template>
          </el-table-column>
        </template>
        <template v-else>
          <el-table-column width="240px" label="任务酬金" prop="budgetAmount">
            <template slot-scope="scope">
              <div>¥{{ scope.row.budgetAmount }}</div>
            </template>
          </el-table-column>
        </template>
        <el-table-column width="240px" label="支付状态">
          <template slot-scope="scope">
            {{ paymentStatuss[scope.row.paymentStatus] }}
          </template>
        </el-table-column>
        <el-table-column width="240px" label="实付金额" prop="paymentAmount">
          <template slot-scope="scope">
            <div v-if="scope.row.paymentAmount">¥{{ scope.row.paymentAmount }}</div>
          </template>
        </el-table-column>
        <el-table-column width="240px" label="支付时间" prop="paymentTime">
        </el-table-column>
        <el-table-column label="操作" width="140px" align="right" fixed="right">
          <template slot-scope="scope">
            <template v-if="taskCommissionStatus">
              <template v-if="scope.row.paymentStatus == '1' || scope.row.paymentStatus == '3'">
                <el-button type="text" size="medium" @click="handleLayer(scope.row)">打款</el-button>
              </template>
            </template>
            <template v-else>
              <template v-if="scope.row.paymentStatus == '3'">
                <el-button type="text" size="medium" @click="handleLayer(scope.row)">打款</el-button>
              </template>
            </template>
            <template v-if="scope.row.paymentStatus != '1'">
              <el-button type="text" size="medium" @click="handleDetails(scope.row)">查看</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="taskInfoListQuery.currentPage"
                     :page-sizes="[10, 20, 50, 100]" :page-size="taskInfoListQuery.size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <!-- 打款弹窗 -->
    <el-dialog :title="financeTitle" :visible.sync="financeVisible" :close-on-press-escape="true" class="payment-box" width="650px">
      <el-form :model="form" label-width="130px" :rules="rules" ref="form" class="pad-t-10">
        <el-form-item label="任务酬金：" prop="amount"><span class="font-red font-18">{{ amount }}</span></el-form-item>
        <el-form-item label="手续费：" prop="chargeAmount"><span class="font-red font-18">{{ chargeAmount }}</span></el-form-item>
        <el-form-item label="支付方式：" prop="paymentType">
            <div class="radio-bar">
              <el-radio-group v-model="form.paymentType" @change="paymentTypeChange(form.paymentType)">
                  <div v-for="type in paymentTypes" class="mar-b-10">
                      <el-radio :label="type.key">
                        <div class="radio-border">
                          <svg-icon :class="type.icon" :icon-class="type.icon" />
                          <span class="radio-txt">{{type.value}}</span>
                        </div>
                      </el-radio>
                  </div>
              </el-radio-group>
            </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="financeVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPayment">确认打款</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="qrCodeVisible" width="12%">
      <img :src="qrCodeUrl" style="width: 200px; height: 200px" />
    </el-dialog>
  </div>
</template>

<style scoped>
.svg-icon{
  margin-right: 6px;

}
.wechatRadius{
  font-size: 26px;
}
.alipay{
  font-size: 60px;
  height: 30px;
}
.radio-txt{
  vertical-align: top;
  display: inline-block;
  padding-top: 6px;
}
.radio-border{
  border:#ccc 1px solid;
  vertical-align: middle;
  display: inline-block;
  padding: 5px 10px;
  width: 150px;
  height: 40px;
}
</style>

<script>
  import { pagingTaskInfoDTO, confirmPayment, pagingAppendAmount, paymentAppendScan, checkPayment } from '@/api/project/taskCommission'
  import QRCode from 'qrcode'

  export default {
    data() {
      return {
        taskInfoList: [],
        paymentStatuss: [],
        starEndTime: [],
        paymentStatus: '',
        taskCommissionStatus: true,
        taskCommissionId: '',
        activeName: '1',
        taskAmountType: '1',
        amount: 0,
        chargeAmount: 0,
        total: null,
        listLoading: true,
        keyword: '',
        keywordType: 'taskName',
        keywordTypeOld: '',
        multipleSelection: [],
        keywordTypes: [{
          value: 'taskName',
          label: '任务名称'
        }],
        taskInfoListQuery: {
          currentPage: 1,
          size: 10,
          startDate: null,
          endDate: null,
          enterpriseId: this.getEnterpriseId(),
          paymentStatus: '1',
          taskName: null
        },
        taskInfo: {
          taskId: '',
          taskType: '',
          taskCode: '',
          taskName: '',
          budgetAmount: '',
          paymentStatus: '',
          paymentAmount: '',
          paymentTime: '',
          taskStatus: '',
          amount: ''
        },
        taskDetail: {
          taskId: '',
          paymentAmount: ''
        },
        financeVisible: false,
        qrCodeVisible: false,
        qrCodeUrl: '',
        financeTitle: null,
        form: {
          taskName: '',
          remunerationType: '1',
          paymentType: '3',
          chargeAmount: 0
        },
        rules: {
          taskName: [
            { required: true, message: '任务酬金', trigger: 'blur' }
          ],
          remunerationType: [
            { required: true, message: '支付方式', trigger: 'blur' }
          ]
        },
        paymentTypes: [
          { key: '3', value: '微信支付', icon: 'wechatRadius' },
          { key: '4', value: '支付宝', icon: 'alipay' }
        ],
        payTypes: [
          { value: '1', label: '待托管' },
          { value: '2', label: '已支付' }
        ],
        payStatus: [
          { value: '1', label: '发布托管酬金' },
          { value: '2', label: '任务追加酬金' }
        ]
      }
    },
    // 过滤器
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      }
    },
    // 初始化页面
    created() {
      this.initTaskInfoList()
    },
    methods: {
      initTaskInfoList() {
        this.taskCommissionStatus = true
        this.taskInfoList = []
        this.listLoading = true
        pagingTaskInfoDTO(this.taskInfoListQuery).then(response => {
          if (response.isError) return
          this.taskInfoList = response.records
          if (response.dict) {
            this.paymentStatuss = response.dict.paymentStatus
          }
          this.total = response.total
          this.listLoading = false
        })
      },
      initTaskCommissionList() {
        this.taskCommissionStatus = false
        this.taskInfoList = []
        this.listLoading = true
        pagingAppendAmount(this.taskInfoListQuery).then(response => {
          if (response.isError) return
          this.taskInfoList = response.records
          if (response.dict) {
            this.paymentStatuss = response.dict.paymentStatus
          }
          this.total = response.total
          this.listLoading = false
        })
      },
      // 列表排序
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'createTime') {
          if (order === 'ascending') {
            this.taskInfoListQuery.ascs = 'createTime'
            this.taskInfoListQuery.descs = ''
          } else {
            this.taskInfoListQuery.ascs = ''
            this.taskInfoListQuery.descs = 'createTime'
          }
        }
        this.initTaskInfoList()
      },
      handleSearch() {
        this.searchReset()
        this.taskInfoListQuery.currentPage = 1
        this.taskInfoListQuery.taskName = this.keyword
        if (this.starEndTime) {
          if (this.starEndTime.length > 0) {
            this.taskInfoListQuery.startDate = this.starEndTime[0]
            this.taskInfoListQuery.endDate = this.starEndTime[1]
          }
        }
        if (this.taskAmountType === '2') {
          // 追加酬金列表页
          if (this.activeName === '1') {
            this.taskInfoListQuery.paymentStatus = 3
          } else {
            this.taskInfoListQuery.paymentStatus = 5
          }
          this.initTaskCommissionList()
        } else {
          this.taskInfoListQuery.paymentStatus = this.activeName
          this.initTaskInfoList()
        }
      },
      changeType() {
        this.handleSearch()
      },
      searchReset() {
        this.taskInfoListQuery = {
          currentPage: 1,
          size: 10,
          startDate: null,
          endDate: null,
          enterpriseId: this.getEnterpriseId(),
          paymentStatus: '',
          taskName: null
        }
      },
      handleSizeChange(val) {
        this.taskInfoListQuery.size = val
        this.initTaskInfoList()
      },
      handleCurrentChange(val) {
        this.taskInfoListQuery.currentPage = val
        this.initTaskInfoList()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 详情
      handleDetails(row) {
        this.$router.push({ path: '/project/task/detail/index', query: { taskId: row.taskId, taskType: row.taskType, taskStatus: row.taskStatus }})
      },
      // 打款
      handleLayer(row) {
        // 打款弹窗页面,设置任务详情为当前行数据
        this.taskDetail = { ...row }
        if (new Date(row.taskEndTime).getTime() > new Date().getTime()) {
          this.taskDetail.taskId = row.taskId
          if (this.taskAmountType === '2') {
            this.amount = row.amount
            this.chargeAmount = row.chargeAmount
            this.taskCommissionId = row.taskCommissionId
          } else {
            this.amount = row.budgetAmount
            this.chargeAmount = row.chargeAmount
          }
          this.taskDetail.taskId = row.taskId
          this.taskDetail.paymentAmount = row.budgetAmount
          this.financeVisible = true
          this.financeTitle = '为保证双方利益，在托管酬金后微客才能报名参与任务'
        } else {
          this.$message.error('任务截止日期必须大于当前日期，请联系客服进行修改')
        }
      },
      // 确认打款
      confirmPayment() {
        if (this.taskAmountType === '2') {
          // 追加酬金打款
          this.taskDetail.paymentType = this.form.paymentType + '2'
          const that = this
          paymentAppendScan({
            taskName: this.taskDetail.taskName,
            payType: this.taskDetail.paymentType,
            taskCommissionId: this.taskCommissionId,
            appendAmount: this.amount
          }).then(response => {
            if (response.isError) return
            QRCode.toDataURL(response.data.resultData)
              .then(url => {
                that.qrCodeUrl = url
                that.qrCodeVisible = true
                that.handlePayByQRCode(that.taskCommissionId, 2)
              })
              .catch(err => {
                console.error(err)
              })
            this.financeVisible = false
          })
        } else {
          // 项目托管 打款
          this.taskDetail.paymentType = this.form.paymentType + '1'
          const that = this
          confirmPayment(this.taskDetail).then(response => {
            if (response.isError) return
            QRCode.toDataURL(response.data.resultData)
              .then(url => {
                that.qrCodeUrl = url
                that.qrCodeVisible = true
                that.handlePayByQRCode(that.taskDetail.taskId, 1)
              })
              .catch(err => {
                console.error(err)
              })
            this.financeVisible = false
          })
        }
      },
      // 扫码支付检测后台是否支付成功
      handlePayByQRCode(id, confirmType) {
        const that = this
        setTimeout(() => {
          checkPayment(id, confirmType).then(response => {
            if (response.isError) return
            if (response.data === 1) {
              // 已支付，刷新页面
              that.qrCodeVisible = false
              this.$message({
                type: 'success',
                message: '支付成功!'
              })
              if (this.taskAmountType === '1') {
                this.initTaskInfoList()
              }
              if (this.taskAmountType === '2') {
                this.initTaskCommissionList()
              }
            } else {
              that.handlePayByQRCode(id, confirmType)
            }
          })
        }, 5000)
      },
      // 更新任务状态
      handleUpdateStatus(row) {
      },
      // 更新支付方式
      paymentTypeChange(paymentType) {
      }
    },
    mounted() {
    }
  }
</script>
